Ext.define('appmod.controller.resources.menu.Startup', {
    extend: 'Ext.app.Controller',

    views: [
    	'resources.menu.Form',
		'resources.menu.Hierarchy'
    ],
	
	models : [
		'resources.AllMenuTreeModel'
	],
	
    stores: [
		'resources.module.AllSel',
		'resources.menu.AllTree',
		'resources.menu.AllSelTree'
	],	

    refs: [
		{ref: 'menuhieraTreePanel',selector:'menuhierarchypanel > allmenutreegrid'},
		{ref: 'menuhieraPanel',selector:'menuhierarchypanel'}
	],

    init: function() {
		
		var me = this;

    	me.control({
			
			'menu-hierarchy-panel  button[action=save]': {
				click:{
					fn:me.updateAllMenuChange,
					scope:me
				}
			},
			
			'menu-hierarchy-panel button[action=addnewmenu]': {
				click:{
					fn:me.showCreateNewMenuForm,
					scope:me
				}
			},

			'menu-hierarchy-panel button[action=removemenu]': {
				click:{
					fn:me.showDelMenuDialog,
					scope:me
				}
			},
			
			'menu-hierarchy-panel button[action=reflesh]' : {
				click:{
					fn:me.refleshMenu,
					scope:me
				}
			},
			
			'menuresourceform button[action=selectParentMenu]' : {
				click:{
					fn:me.selectParentMenu,
					scope:me
				}
			},
			
			'menuresourceform button[action=clearParentMenu]' : {
				click:{
					fn:me.clearParentMenu,
					scope:me
				}
			},
						
			'menuresourceform button[action=reset]': {
				click:this.resetMenuForm
			}			
						
    	});

    },

	
	loadInitComp : function() {
		var me = this;
		var menuAllTree = me.getResourcesMenuAllTreeStore();
	
		var mainPanel =	Ext.create('Ext.tab.Panel', {
                    activeTab:0,
                    region:'center',
                    plain: true,
                    items:[
                        {
							store:menuAllTree,
							xtype:'menu.hierarchy.panel',
							title:'菜单组织结构'	
						}
						/*
						,
                        Ext.create('appmod.view.resources.MenuDashboard'),
						Ext.create('appmod.view.resources.MenuRegDashboard')
						*/
                    ]
              
            
    	});	
		return mainPanel;		
	},
	
	// --- use this app lication
	onLaunch:function(app) {

		var me = this;


	},	

	updateAllMenuChange:function() {
		var me = this;
		
		var menuhieraTreePanel = me.getMenuhieraTreePanel();

		var store = menuhieraTreePanel.getStore();

		//var store = me.getResourcesModuleAllFunsStore();

		var proxy =store.getProxy();
		store.sync({
			callback:function(batch , options) {
				//alert('callback');
			},
			success:function(batch , options) {
				if ( batch.isComplete) {
					Ext.MessageBox.show({
        				title: "提示",
        				msg: '菜单更新成功',
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
				}
			},
			failure:function(batch , options) {
				//alert('failure');
			}
		});


	},
	
	menuTreeChangeSave:function() {
		
		var me = this;

		var menuhieraPanel = me.getMenuhieraPanel();
		var menuhieraTreePanel = me.getMenuhieraTreePanel();

		var store = menuhieraTreePanel.getStore();
		var updatedRecords = store.getUpdatedRecords();
		
		var jsonData = [];
		
		// --- get update record s ---
		for (var i =0 ; i < updatedRecords.length ; i++) {
			var record = updatedRecords[i];
			
			var node = store.getNodeById(record.getId() );
			var updateItem = {
				method : 'update',
				id : record.getId(),
				code : record.get('code'),
				parentId : node.parentNode.getId()
			}
			jsonData.push( updateItem );
		}
		
		// --- remove record ---
		var removedRecords = store.getRemovedRecords();
		for (var i =0 ; i < removedRecords.length ; i++) {
			var record = removedRecords[i];
			var removeItem = {
				method : 'delete',
				id : record.getId()
			}
			jsonData.push( removeItem );
			
		}
		
		/// --- using ajax ---
		// --- update record using ajax
		try {

			Ext.Ajax.request({
				url: '../../data/resource/resources/menu/merge_all.json',
				method:'post',
				/*
				params:{
					'jsonData':Ext.encode(jsonData)
				},
				*/
				jsonData:jsonData,
				success: function(response, opts) {
					 
					 var obj = Ext.decode(response.responseText);
					 
					 // --- popup message ---
					Ext.MessageBox.show({
        				title: "提示",
        				msg: obj.msg,
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
					
					// --- reload ---
					

				},
				failure: function(response, opts) {
				
				}
			});

			
		} catch (e) {
			alert(e);
		}		
		
		
	},

	
	refleshMenu :function() {
		var me = this;
		var menuhieraPanel = me.getMenuhieraTreePanel();
		var store = menuhieraPanel.getStore();
		store.load();
	},

	
	// --- add new menu ---
	showCreateNewMenuForm:function() {
		
		var me = this;

		// --- whether select menu   ---
		var menuhieraPanel = me.getMenuhieraTreePanel();
		var selectionModel = menuhieraPanel.getSelectionModel();
		var records = selectionModel.getSelection();
		
		
		var dsModAllSel = me.getResourcesModuleAllSelStore();
		dsModAllSel.reload();
 
		var dsParent = me.getResourcesMenuAllSelTreeStore();
		dsParent.reload();
		var fieldStores = {
			'dsModAllSel' : dsModAllSel,
			'dsParent' : dsParent
		}
		
		// --- build new form ---
		var win = null;
		if (!win) {
			win = new Ext.create('widget.window', {
				modal:	true,
				title : '菜单资料',
				closable : true,
				closeAction:'hide',
				width : 500,
				height : 300,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					fieldStores:fieldStores,
					padding : 5,
					xtype : 'menu-form',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '保 存',
							action:'addNewMenu'
        				},{
            				text: '重 置',
							action:'reset'
        				}
				    ]
				}]				

			});
		}
		
		
		// --- get the current form panel ---
		var formPanel = win.down("menu-form");

		var form = formPanel.getForm();

		var saveBtn = win.down('button[action="addNewMenu"]');
		saveBtn.on("click",me.saveNewMenu , me , {
			window: win
		});
		
		if (records.length > 0) {
			// --- init object --- 
			var initValue = {
				parentName : records[0].get('text'),
				parentId: records[0].get('id')
			}
			form.setValues(initValue);			
		}
		
		if ( !win.isVisible() ) {
			win.show();
		}
	},
	
	saveNewMenu:function(me , event , eOpts) {
		
		var me = this;

		var upWin = eOpts.window;
		
		var formPanel = upWin.down('menu-form');

		var form = formPanel.getForm();
		
		var menuhieraTreePanel = me.getMenuhieraTreePanel();
		
		if ( form.isValid() ) {

			// --- submit form 
			form.submit({
				url:'../../data/resource/resources/menu/submit_adding.json',			
				success:function(form, action) {
					Ext.Msg.alert('成功', action.result.msg);

					 if (upWin.isVisible()) {
					 	upWin.close();
					 }
					 
					 var store = menuhieraTreePanel.getStore();
					 if (store) {
					 	store.reload();
					 }					


				},
				failure:function(form, action) {
					switch (action.failureType) {
						case Ext.form.action.Action.CLIENT_INVALID:
							Ext.Msg.alert('失败', '表单里包含错误的信息');
							break;
						case Ext.form.action.Action.CONNECT_FAILURE:
							Ext.Msg.alert('失败', '服务器连接失败,请联系管理人员');
							break;
						case Ext.form.action.Action.SERVER_INVALID:
							Ext.Msg.alert('失败', action.result.msg);
					}
				}
			});
			
		}
	},


	
	resetMenuForm : function() {
		var form = Ext.getCmp('menuresourceform');

		form.getForm().reset();
					
	},
	
	showDelMenuDialog:function(item, eventObj, eOpts) {
		var me = this;

		// --- get contact person id ---
		var menuhiPanel = me.getMenuhieraTreePanel();
		
		var records = menuhiPanel.getView().getChecked();
		
		// --- select resource --
		var removeRecs = "";
		for (var i = 0 ; i < records.length ; i++) {
			if (removeRecs.length != 0 ) {
				removeRecs += ",";
			}
			if ( !records[i].hasChildNodes() ) {
				removeRecs += records[i].get('text');
			}
		}
		if (removeRecs == "") {
			return;
		}
		Ext.MessageBox.confirm('确认', '确定要删除媒体: "'+removeRecs+'"?',me.confirmDelMenus , me);		
			
	},
	
	confirmDelMenus:function(confirm) {
		var me = this;
		
		var menuhiPanel = me.getMenuhieraTreePanel();
		
		var records = menuhiPanel.getView().getChecked();
		
		if (confirm == "no") {
			return;
		}

		var jsonObj = [];
		for (var i = 0 ; i < records.length ; i++) {
			jsonObj.push(records[i].getId());
		}

		
		// --- update record using ajax
		try {

			Ext.Ajax.request({
				url: '../../data/resource/resources/menu/submit_deleteall.json',
				method:'post',
				jsonData:jsonObj,
				success: function(response, opts) {

					 var store = menuhiPanel.getStore();
					 if (store) {
					 	store.reload();
					 }	
										 
     				var obj = Ext.decode(response.responseText);
					 
					 // --- popup message ---
					Ext.MessageBox.show({
        				title: "提示",
        				msg: obj.msg,
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
					
					// --- reload ---

				},
				failure: function(response, opts) {
					alert("error alert for deleting provider contact person!");
		
				}
			});

			
		} catch (e) {
			Ext.log({
				msg:'error : ' + e
			})
		}			
	},	
	
	removeMenu : function() {
		
		me = this;
		
		var menuhiPanel = me.getMenuhieraTreePanel();
		
		var menuhieraPanel = me.getMenuhieraPanel();
		
		var records = menuhiPanel.getView().getChecked();

		for (var i = records.length -1  ; i >= 0 ; i--) {
			// --- record ---
			 records[i].remove();
			 menuhieraPanel.getChangedRecord().add( records[i].getId() , 'delete' );
		}


	},
	
	selectParentMenu:function() {
		
		var me = this;

		var dsMenuAllTree = me.getResourcesMenuAllTreeStore();
	
		
		// --- build new form ---
		if (!this.winForMenuTree) {
			this.winForMenuTree = new Ext.create('widget.window', {
				title : '菜单结构图',
				modal : true,
				closable : true,
				closeAction:'hide',
				width : 500,
				height : 400,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					id:'allmenutreegrid',
					xtype : 'allmenutreegrid',
        			useArrows: true,
					multiSelect: false,
        			rootVisible: false,					
					store: dsMenuAllTree,
					region:'center'
				}],
				dockedItems: [{
            		xtype: 'toolbar',
            		dock: 'bottom',
            		ui: 'footer',
            		layout: {
                		pack: 'end'
            		},
            		items: [{
                		minWidth: 80,
                		text: '选择关闭',
						scope : me,
						handler : me.selectAndCloseParentWindow
            		}]
	        	}]
			});
		}
		
		if ( this.winForMenuTree.isVisible() ) {
			
		} else {
			this.winForMenuTree.show();
		}		
		
	},
	
	selectAndCloseParentWindow : function() {
		var treeGrid = Ext.getCmp('allmenutreegrid');
		var selMod = treeGrid.getSelectionModel();
		var records = selMod.getSelection();
		
		
		var form = Ext.getCmp('menuresourceform');
		var textfieldssels = form.query("textfield[name=parentName]");
		var idsParentSelected = form.query("hiddenfield[name=parentId]");
		

		textfieldssels[0].setValue( records[0].get('text') );
		idsParentSelected[0].setValue( records[0].id );

		
		if ( this.winForMenuTree.isVisible() ) {
			this.winForMenuTree.hide();
		} 		
		
	},
	
	clearParentMenu:function() {
		
		var form = Ext.getCmp('menuresourceform');
		var textfieldssels = form.query("textfield[name=parentName]");
		var idsParentSelected = form.query("hiddenfield[name=parentId]");
		
		textfieldssels[0].setValue('' );
		idsParentSelected[0].setValue( '');
				
		

	}
	
});